<template>
  <div>
    <img
      :src="captchaImgUrl" alt="验证码" title="点击刷新验证码"
      @click="refreashCaptcha"
    >
    <i style="color: #1296db;" :class="validIcon" />
  </div>
</template>

<script>
import { axios, post, get } from '../../../utils/https';
// import Message from '../../message';
// import ElFormItem from '../../form-item';
// import ElCol from '../../col';
// import ElInput from '../../input';

const captchaServletUrl = SERVICE_URL + '/captcha/refresh'; // 刷新验证码
const validServletUrl = SERVICE_URL + '/captcha/validate'; // 验证码验证

export default {
  name: 'ValidCode',
  // components: { ElFormItem, ElCol, ElInput },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    captcha: String,
    validIcon: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      captchaImgUrl: '',
      sessionId: '',
      ticket: ''
      // captcha:''
    };
  },
  computed: {},
  created() {
    this.refreashCaptcha();
  },
  methods: {
    // 验证码刷新
    refreashCaptcha() {
      let data = '';
      this.$emit('refreash');
      if (this.sessionId) {
        data = this.sessionId;
      }
      post(
        captchaServletUrl,
        {
          data: data
        },
        (resp) => {
          this.captchaImgUrl = resp.data.data.src;
          this.sessionId = resp.data.data.sessionId;
        },
        (err) => {
          Message.error(err.message);
        }
      );
    },
    // 验证码验证
    validateCaptcha() {
      const _this = this;
      post(
        validServletUrl,
        {
          data: {
            sessionId: _this.sessionId,
            word: _this.captcha
          }
        },
        (resp) => {
          if (!resp.data.result) {
            _this.$emit('error', resp.data.msg);
          } else {
            _this.ticket = resp.data.data;
            _this.$emit('receive', _this.sessionId, _this.ticket);
          }
        },
        (err) => {
          Message.error(err.message);
        }
      );
    }
  }
};
</script>

